package com.rongmei.jdsync.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

/**
 * 价格变更数据传输对象
 *
 * @author dongjun
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "价格变更数据传输对象")
public class PriceChangeDto {

    @Schema(description = "商品ID", example = "25862", required = true)
    @JsonProperty("goods_id")
    @NotNull(message = "商品ID不能为空")
    private Long goodsId;

    @Schema(description = "商品名称", example = "姚生记A180大颗粒紫皮腰果仁500g")
    @JsonProperty("goods_name")
    private String goodsName;

    @Schema(description = "旧价格", example = "48.48", required = true)
    @JsonProperty("old_price")
    @NotNull(message = "旧价格不能为空")
    private BigDecimal oldPrice;

    @Schema(description = "新价格", example = "45.99", required = true)
    @JsonProperty("new_price")
    @NotNull(message = "新价格不能为空")
    private BigDecimal newPrice;

    @Schema(description = "价格变更时间")
    @JsonProperty("change_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime changeTime;

    @Schema(description = "变更金额", example = "-2.49")
    @JsonProperty("change_amount")
    private BigDecimal changeAmount;

    @Schema(description = "变更百分比", example = "-5.14")
    @JsonProperty("change_percentage")
    private BigDecimal changePercentage;

    @Schema(description = "变更类型：1-涨价，-1-降价，0-无变化")
    @JsonProperty("change_type")
    private Integer changeType;

    @Schema(description = "是否为重大变更（变更幅度超过阈值）")
    @JsonProperty("is_major_change")
    private Boolean isMajorChange = false;

    /**
     * 计算价格变更信息
     * 包括变更金额、变更百分比、变更类型等
     */
    public void calculateChange() {
        if (oldPrice == null || newPrice == null) {
            return;
        }

        // 计算变更金额
        this.changeAmount = newPrice.subtract(oldPrice);

        // 计算变更百分比
        if (oldPrice.compareTo(BigDecimal.ZERO) > 0) {
            this.changePercentage = changeAmount
                    .divide(oldPrice, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);
        } else {
            this.changePercentage = BigDecimal.ZERO;
        }

        // 确定变更类型
        int comparison = changeAmount.compareTo(BigDecimal.ZERO);
        if (comparison > 0) {
            this.changeType = 1;  // 涨价
        } else if (comparison < 0) {
            this.changeType = -1; // 降价
        } else {
            this.changeType = 0;  // 无变化
        }

        // 设置变更时间
        this.changeTime = LocalDateTime.now();
    }

    /**
     * 判断是否为重大价格变更
     * 
     * @param threshold 变更阈值（元）
     * @return 是否为重大变更
     */
    public boolean isMajorChange(BigDecimal threshold) {
        if (changeAmount == null || threshold == null) {
            return false;
        }
        
        BigDecimal absChangeAmount = changeAmount.abs();
        this.isMajorChange = absChangeAmount.compareTo(threshold) >= 0;
        return this.isMajorChange;
    }

    /**
     * 判断是否为重大价格变更（按百分比）
     * 
     * @param percentageThreshold 变更百分比阈值
     * @return 是否为重大变更
     */
    public boolean isMajorChangeByPercentage(BigDecimal percentageThreshold) {
        if (changePercentage == null || percentageThreshold == null) {
            return false;
        }
        
        BigDecimal absChangePercentage = changePercentage.abs();
        this.isMajorChange = absChangePercentage.compareTo(percentageThreshold) >= 0;
        return this.isMajorChange;
    }

    /**
     * 获取变更描述
     * 
     * @return 变更描述文本
     */
    public String getChangeDescription() {
        if (changeAmount == null || changePercentage == null) {
            return "价格变更信息不完整";
        }

        String direction = changeType > 0 ? "上涨" : (changeType < 0 ? "下降" : "无变化");
        return String.format("价格%s %.2f元 (%.2f%%)", 
                direction, 
                changeAmount.abs(), 
                changePercentage.abs());
    }

    /**
     * 验证价格变更数据的有效性
     * 
     * @return 是否有效
     */
    public boolean isValid() {
        return goodsId != null && 
               oldPrice != null && 
               newPrice != null && 
               oldPrice.compareTo(BigDecimal.ZERO) >= 0 && 
               newPrice.compareTo(BigDecimal.ZERO) >= 0;
    }

    /**
     * 创建价格变更DTO的便捷方法
     * 
     * @param goodsId 商品ID
     * @param goodsName 商品名称
     * @param oldPrice 旧价格
     * @param newPrice 新价格
     * @return 价格变更DTO
     */
    public static PriceChangeDto create(Long goodsId, String goodsName, 
                                       BigDecimal oldPrice, BigDecimal newPrice) {
        PriceChangeDto dto = new PriceChangeDto();
        dto.setGoodsId(goodsId);
        dto.setGoodsName(goodsName);
        dto.setOldPrice(oldPrice);
        dto.setNewPrice(newPrice);
        dto.calculateChange();
        return dto;
    }

    @Override
    public String toString() {
        return String.format("PriceChangeDto{goodsId=%d, goodsName='%s', oldPrice=%s, newPrice=%s, changeAmount=%s, changePercentage=%s%%}", 
                goodsId, goodsName, oldPrice, newPrice, changeAmount, changePercentage);
    }
}
